/**
 * 
 */
package com.robot.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.robot.dao.PasswordDao;
import com.robot.dao.UserDao;
import com.robot.dto.UserDTO;
import com.robot.dto.util.UserHelperDto;
import com.robot.exception.InvalidUserException;
import com.robot.model.Password;
import com.robot.model.User;
import com.robot.service.UserService;

/**
 * @author johnny Esta clase implemente los metodos de la interface UserService
 *         y sirve para crear la logica de negocio antes y despues de acceder a
 *         los datos en la BD.
 * 
 */
@Component
public class UserServiceImpl implements UserService, Serializable {

	private static final long serialVersionUID = 1L;

	@Autowired
	UserDao userDao;

	@Autowired
	PasswordDao passwordDao;

	public UserServiceImpl() {
		System.out.println("se instancia objeto de la clase UserServiceImpl");
	}

	@Override
	public UserDTO findOne(Long id) {
		User user = userDao.findOne(id);
		UserDTO userDTO = new UserDTO();
		userDTO = UserHelperDto.convertToDto(user);
		return userDTO;

	}

	@Override
	public List<UserDTO> listAllUsers() {
		List<User> users = userDao.findAll();
		List<UserDTO> listDTOUsers = new ArrayList<UserDTO>();
		for (User user : users) {
			UserDTO userDTO = new UserDTO();
			userDTO = UserHelperDto.convertToDto(user);
			listDTOUsers.add(userDTO);
		}

		return listDTOUsers;
	}

	@Override
	public UserDTO findByUserName(String userName) {
		User user = userDao.findByUserName(userName);
		UserDTO userDTO = new UserDTO();
		userDTO = UserHelperDto.convertToDto(user);
		return userDTO;
	}

	@Override
	public void eliminarUsuario(Long id) {
		userDao.delete(id);
	}

	public UserDTO saveUser(UserDTO userDto) throws InvalidUserException {
		User newUserEntity = new User();

		// hace el paser desde el DTO a la entidad
		newUserEntity = UserHelperDto.convertToEntity(userDto);
		List<Password> userPasswords = new ArrayList<Password>();// esta

		Password newpasswordEntity = new Password();

		newpasswordEntity.setPassword(userDto.getPassword());
		newpasswordEntity.setStatus(1);
		userPasswords.add(newpasswordEntity);// esta linea setea el arreglo
		newUserEntity.setPasswords(userPasswords);
		User newUser = userDao.save(newUserEntity);
		newpasswordEntity.setUser(newUser);
		passwordDao.save(newpasswordEntity);

		System.out.println("UserServiceImpl.saveUser  --- [ok] ");
		return userDto;
	}

	public List<UserDTO> listUser() {
		// TODO Auto-generated method stub
		return null;
	}

}
